import axios from 'axios'
import store from 'store'

import { decrypt } from './interface'
import getHttpStatusText from 'utils/getHttpStatusText'

export default (state) => {
  const token = store.get('token')
  axios.defaults.headers.common['Authorization'] = token
  axios.interceptors.request.use(cfg => {
    return cfg
  }, err => [err.toString()])

  axios.interceptors.response.use(res => {
    let {
      data: {
        code,
        data,
        message
      }
    } = res

    if (code !== '0') {
      return [message || '请求错误']
    }

    // data = decrypt(data)
    // console.log(data)

    return [null, {
      code,
      message,
      data,
    }, res]
  }, err => {
    const { error, config, code, request, response } = err

    if (!response) {
      return ['未连接到服务器']
    }

    // 还是需要返回错误原信息,因为接口需要传递发送信息与接口的信息
    if (response.status) {
      return [getHttpStatusText(response.status), err]
    }

    return ['连接失败', err]
  })
}
